<script setup>
import { computed, ref } from "vue";
import { httpRequest } from "../../utils/http";
import { useStore } from "../../store/store";
const store = useStore();
console.log(store);
const price = ref(1); //单价
const num = ref(1); //数量
const payInfoName = ref(""); //商品名称
const orderNum = ref(""); //订单号
const openId = ref(""); //openId
const signature = ref(""); //签名
const payInfoArr = ref([])
const radioIndex = ref(0)
const sum = computed(() => {
  return price.value * num.value;
});
//获取商品信息
const getPayInfo = async () => {
  const res = await httpRequest("/api/agentProductById", "POST", {
    id: store.userInfo.agentId,
  });
  console.log(res);
  payInfoArr.value = res.data;
  price.value = res.data[0].price
  payInfoName.value = res.data[0].productName
  const data = await httpRequest("/api/agentPaymentInfo", "POST");
  console.log(data);
  orderNum.value = data.data;
};
getPayInfo();

//获取openID
const getOpenId = async () => {
  uni.login({
    provider: "weixin",
    success: async (res) => {
      console.log(res.code);
      const res1 = await httpRequest("/api/jscode2session", "POST", { code: res.code });
      console.log(res1);
      console.log(JSON.parse(res1.data));
      openId.value = JSON.parse(res1.data).openid;
    },
  });
};
getOpenId();
//获取签名
const getPerpaySignature = async () => {
  console.log(openId.value);
  const res = await httpRequest("/api/getPerpaySignature", "POST", {
    method: "POST",
    url: "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi",
    body: JSON.stringify({
      appid: "wxb2ccb9a787fd1b72",
      mchid: "1656084688",
      description: payInfoName.value,
      out_trade_no: orderNum.value,
      notify_url: "https://www.xingchengwenhua.com:8081/api/orderResult",
      // notify_url: "https://www.xingchengwenhua.com:8081/api/orderResult",
      amount: { total: sum.value * 100 },
      payer: { openid: openId.value },
    }),
  });
  console.log(res);
  signature.value = res.data;
};

//JSAPI下单
const placeOlder = async () => {
  await getPerpaySignature();
  // if (checked.value[0] != "cd")
  //   return uni.showToast({ title: "请先勾选协议", icon: "none" });
  //JSAPI下单
  uni.request({
    url: "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi",
    method: "POST",
    header: {
      Authorization: `WECHATPAY2-SHA256-RSA2048 ${signature.value},`,
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    data: JSON.stringify({
      appid: "wxb2ccb9a787fd1b72",
      mchid: "1656084688",
      description: payInfoName.value,
      out_trade_no: orderNum.value,
      // notify_url: "https://www.xingchengwenhua.com:8081/api/orderResult",
      notify_url: "https://www.xingchengwenhua.com:8081/api/orderResult",
      amount: { total: sum.value * 100 },
      payer: { openid: openId.value },
    }),
    success: async (res) => {
      console.log(res);
      const res1 = await httpRequest("/api/getZFPageSignature", "POST", {
        appId: "wxb2ccb9a787fd1b72",
        prepayId: `prepay_id=${res.data.prepay_id}`,
      });
      console.log(res1);
      console.log(sum.value * 100);
      console.log(!store.userInfo.agentId);
      console.log(!num.value);
      console.log(!sum.value);
      console.log(!orderNum.value);
      console.log(payInfoArr.value[radioIndex.value]);
      if(!orderNum.value||!store.userInfo.agentId||!num.value||!sum.value||!payInfoArr.value[radioIndex.value].id)return uni.showToast({title:"出错了,请重试",icon:'none'})
      uni.requestPayment({
        provider: "wxpay",
        orderInfo: {
          description: payInfoName.value,
          price: sum.value * 100,
          orderNum: orderNum.value,
        },
        timeStamp: res1.data.timeStamp.toString(),
        nonceStr: res1.data.nonceStr,
        package: `prepay_id=${res.data.prepay_id}`,
        signType: "RSA",
        paySign: res1.data.paySign,
        success: async (res2) => {
          console.log(res2);
          const res3 = await httpRequest("/api/getAgentOrderInfo", "POST", {
            orderNumber: orderNum.value,
            agentId: store.userInfo.agentId,
            kaNum: num.value,
            price: sum.value,
            productId: payInfoArr.value[radioIndex.value].id,
          });
          console.log(res3);
          if (!res3.success) {
            uni.showToast({
              title: "支付取消",
              icon: "none",
            });
            setTimeout(() => {
              uni.switchTab({ url: "/pages/index/index" });
            }, 1000);
            return;
          }

          //提示用户
          uni.showToast({
            title: "支付成功",
            icon: "success",
            mask: true,
          });
          //跳转页面
          setTimeout(() => {
            uni.redirectTo({ url: "/pages/index/payCardInfo" });
          }, 1000);
        },
        fail: (error) => {
          console.log(error);
          uni.showToast({
            title: "支付取消",
            icon: "none",
          });
          setTimeout(() => {
            uni.switchTab({ url: "/pages/index/index" });
          }, 1000);
        },
      });
    },
  });
};
const checked = ref([]);
const checkedBox = (e) => {
  console.log(e.detail);
  checked.value = e.detail.value;
};
const goAgent = () => {
  uni.navigateTo({ url: "/pages/index/agent" });
};

const radioChange = (e) => {
  console.log(e.detail.value);
  price.value = payInfoArr.value[e.detail.value].price
  payInfoName.value = payInfoArr.value[e.detail.value].productName
  radioIndex.value = e.detail.value
  console.log(payInfoArr.value[Number(radioIndex.value)]);
}
</script>

<template>
  <view class="page">
    <view class="product">
      <!-- <view class="shop">
        <image class="shop-image" src="../../static/list_jcban.png" mode="" />
        <view class="introduce">
          <text class="name">店店有客年卡</text>
          <text class="edition">{{ payInfoName }}</text>
          <text class="price">{{ price }}<text class="yuan">.00元</text></text>
        </view>
      </view> -->
      <view>
        <radio-group @change="radioChange">
          
            <scroll-view scroll-x class="scroll">
              <view class="item" v-for="item,index in payInfoArr" :key="item.id">
                <label>
                <view class="banben">
                  <text>{{ item.productName }}</text>
                  <radio color="rgb(64,158,255)" :value="index" :checked="index==0"/>
                </view>
                <view class="num">{{item.videoNum}}次 <text style="font-size: 24rpx;color: rgb(144,147,153);">(合成额度)</text></view>
                <text class="price">￥<text style="font-size: 28rpx;">{{item.price}}</text></text>
                </label>
              </view>
            </scroll-view>
        </radio-group>
      </view>
    </view>
    <view class="form">
      <view class="uprice">
        <text>单价</text>
        <text>￥{{ price }}</text>
      </view>
      <view class="num">
        <text>数量</text>
        <uni-number-box :min="1" v-model="num"></uni-number-box>
      </view>
      <view class="total">
        <text>商品总价</text>
        <text>￥{{ sum }}</text>
      </view>
      <view class="actual"
        >共计{{ num }}张 实际支付￥<text class="sum">{{ sum }}</text
        >元</view
      >
    </view>
    <view class="annual">
      <view class="top">
        <text>年卡介绍</text>
      </view>
      <view class="bottom">
        <view>卡额：十二个月（365天）</view>
        <view class="margin">合成视频数量：3650次</view>
        <view style="margin-bottom: 30rpx"
          ><text style="font-weight: 700">有效期：</text
          >激活后365天到期（未使用完卡额不支持延期/退订）</view
        >
        <view><text style="font-weight: 700">期限卡退订规则：</text>不支持退订</view>
      </view>
    </view>
    <view class="pay">
      <!-- <view class="agreement">
        <checkbox-group @change="checkedBox">
          <checkbox
            color="rgba(64,158,255,1)"
            style="transform: scale(0.75); margin-right: 12rpx"
            value="cd"
          />我已阅读并同意
        </checkbox-group>
        <text @click="goAgent" style="color: rgb(64, 158, 255)">《用户协议》</text>
        <text>和</text>
        <text @click="goAgent" style="color: rgb(64, 158, 255)">《隐私协议》</text>
      </view> -->
      <view>
        <button class="btn" @click="placeOlder()">立即支付</button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.page {
  padding-bottom: 300rpx;
  .product {
    padding: 30rpx;
    background-color: #fff;
    .shop {
      width: 690rpx;
      height: 208rpx;
      display: flex;
      padding: 24rpx;
      box-sizing: border-box;
      background-color: #fff;
      .shop-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 28rpx;
        margin-right: 24rpx;
      }
      .introduce {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .name {
          font-size: 36rpx;
          font-weight: 700;
          color: rgb(69, 70, 74);
        }
        .edition {
          font-size: 24rpx;
          color: rgb(144, 147, 153);
        }
        .price {
          font-size: 32rpx;
          color: rgb(255, 55, 71);
          font-weight: 700;
          margin-top: 12rpx;
          margin-bottom: 10rpx;
          .yuan {
            font-size: 24rpx;
          }
        }
      }
    }
    .scroll{
      white-space: nowrap;
      height: 250rpx;
      // background-color: #fff;
      .item{
        width: 390rpx;
        height: 232rpx;
        border-radius: 24rpx;
        padding: 34rpx 30rpx;
        box-sizing: border-box;
        background-color: #fff;
        display: inline-block;
        border: 1px solid rgb(220, 223, 230);
        margin-right: 18rpx;
        .banben{
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 28rpx;
          color: rgb(64, 158, 255);
          margin-bottom: 20rpx;
        }
        .num{
          font-size: 40rpx;
          font-weight: 700;
          color: rgb(48,49,51);
          margin-bottom: 6rpx;
        }
        .price{
          font-size: 28rpx;
          color: rgb(144, 147, 153);
        }
      }
    }
  }
  .form {
    padding: 30rpx;
    box-sizing: border-box;
    background-color: #fff;

    .uprice {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 104rpx;
      font-size: 30rpx;
      color: rgb(69, 70, 74);
    }
    .num {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 104rpx;
      font-size: 30rpx;
      color: rgb(69, 70, 74);
      border-bottom: 1rpx solid rgb(220, 223, 230);
    }
    .total {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 30rpx;
      color: rgb(69, 70, 74);
      margin-top: 30rpx;
    }
    .actual {
      font-size: 32rpx;
      margin-top: 18rpx;
      margin-bottom: 30rpx;
      font-weight: 700;
      text-align: right;
      color: rgb(69, 70, 74);
      .sum {
        color: rgb(255, 55, 71);
      }
    }
  }
  .annual {
    box-sizing: border-box;
    padding: 0 30rpx;
    background-color: #fff;
    margin-top: 30rpx;
    .top {
      height: 108rpx;
      display: flex;
      align-items: center;
      font-size: 32rpx;
      font-weight: 700;
      color: rgb(48, 49, 51);
      border-bottom: 1rpx solid rgb(220, 223, 230);
    }
    .bottom {
      padding: 30rpx 0;
      font-size: 28rpx;
      color: rgb(69, 70, 74);
      .margin {
        margin: 30rpx 0;
      }
    }
  }
  .pay {
    box-sizing: border-box;
    position: fixed;
    bottom: 0;
    left: 0;
    height: 128rpx;
    background-color: #fff;
    padding: 0 30rpx;
    .agreement {
      height: 96rpx;
      display: flex;
      align-items: center;
      font-size: 24rpx;
    }
    .btn {
      width: 690rpx;
      height: 88rpx;
      margin-top: 10rpx;
      border-radius: 8rpx;
      background-color: rgb(64, 158, 255);
      text-align: center;
      line-height: 88rpx;
      color: #fff;
      font-size: 32rpx;
    }
  }
}
</style>
